<?php

/**
 * EGGMS 进货预计
 * ============================================================================
 * 网站地址: http://www.eggms.com；
 * ============================================================================
 * $Author: 王海龙 $
 * $Id: sale_satts.php 17217 2014-09-11 08:45 王海龙 $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/admin/statistic.php');
@ini_set('display_errors',        1);

$smarty->assign('lang', $_LANG);

/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'view';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

/*------------------------------------------------------ */
//--订单统计
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'view')
{
    admin_priv('sale_order_stats');

    $end_date = !empty($_REQUEST['end_date'])?$_REQUEST['end_date']:(date("Y-m-d"));//结束日期
    $start_date = !empty($_REQUEST['start_date'])?$_REQUEST['start_date']:(date("Y-m-d",strtotime('-7 day',strtotime($end_date))));//开始日期
    $start_time = strtotime($start_date);//开始时间戳
    $end_time = strtotime($end_date);//结束时间戳
    $sort = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : 'P';
    $type = !empty($_REQUEST['type']) ? $_REQUEST['type'] : 'ASC';

    /* 获取商品进货所需信息（进货商、物流上架时间） */
    $sql = "SELECT sku, biz, ldate FROM egg_ware_goods_biz";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $bizArr[$row['sku']] = $row;
    }

    // 取得订单商品销售量
    /* 先获取当前时间段的有效订单 */
    $sql = "SELECT order_id FROM egg_order_info WHERE order_status IN (1, 5) AND user_id != 3 AND add_time >= $start_time AND add_time < $end_time";
    $orderIdArr = $db->getCol($sql);
    $orderIdStr = implode(',', $orderIdArr);

    /* 获取当前时间段所有商品的销量（除淘蛋商品） */
    $sql = "SELECT goods_id, goods_attr_id, SUM(goods_number) AS sales, goods_sku, goods_attr_sku, IF(goods_attr_sku, goods_attr_sku, goods_sku) AS sku, goods_name, goods_attr FROM egg_order_goods WHERE order_id IN ($orderIdStr) AND goods_id != 0 GROUP BY goods_id, goods_attr_id ORDER BY SUM(goods_number) DESC";

    $goodsArr = $GLOBALS['db']->getAll($sql);

    /* 查询当前正在进货的商品 */
    $sql = "SELECT id, sku, name, add_time FROM egg_ware_purchases WHERE is_check = 0 ORDER BY add_time DESC";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $purchases[$row['sku']] = $row;
    }

    /* 过滤正在进货中的商品 */
    foreach ($goodsArr as $key => $value) {
        if (!empty($value['sku'])) {
            $skuArr2[] = $value['sku'];
        }
        if (!empty($purchases[$value['sku']])) {
            /* 如果当前商品正在进货中，则不进行进货预警 */
            unset($goodsArr[$key]);
            continue;
        }
        if (!empty($value['sku'])) {
            $skuArr[] = $value['sku'];
        }
    }

    /* SQL查询IN操作条件 */
    $skuStr = implode(',', $skuArr);

    /* 查询有销量的商品的库存 */
    $sql = "SELECT goods_id, goods_attr_id, goods_sku AS sku, goods_number AS stock, goods_xprice FROM egg_goods_stock WHERE goods_sku IN ($skuStr)";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $goodsStockArr[$row['sku']] = $row;
    }
    /* 过滤是否预警提醒 */
    foreach ($goodsArr as $key => $value) {
        // 当前统计时间（天）
        $T = ceil(($end_time-$start_time)/86400);
        // 日平均销售量
        $ST = sprintf('%.2f', $value['sales']/$T);
        // 物流时间
        $Q = !empty($bizArr[$value['goods_sku']]['ldate']) ? $bizArr[$value['goods_sku']]['ldate'] : 7;
        // 离账期剩余天数
        $A = ceil((strtotime(date('Y-m-01', strtotime('+1 month'))) - time())/86400);
        // 当前库存
        $S = !empty($goodsStockArr[$value['sku']]['stock']) ? $goodsStockArr[$value['sku']]['stock'] : 0;
        // 当前库存支撑时间(天)
        $P = sprintf('%.2f', $S / $ST) >= 0 ? sprintf('%.2f', $S / $ST) : 0;
        // 建议采购量
        $Z = (($A <= $Q) ? ($Q + 1) : $A) * $ST;
        /* 如果支撑时间小于等于物流时间，则进行预警，否则取消预警 */
        if ($P - 5 < $Q) {
            $goodsArr[$key]['S'] = $S;
            $goodsArr[$key]['ST'] = $ST;
            $goodsArr[$key]['Q'] = $Q;
            $goodsArr[$key]['A'] = $A;
            $goodsArr[$key]['P'] = $P;
            $goodsArr[$key]['Z'] = $Z;
            $goodsArr[$key]['goods_xprice'] = !empty($goodsStockArr[$value['sku']]['goods_xprice']) ? $goodsStockArr[$value['sku']]['goods_xprice'] : '0.00';
            $goodsArr[$key]['B'] = !empty($bizArr[$value['goods_sku']]['biz']) ? $bizArr[$value['goods_sku']]['biz'] : '无';
        } else {
            unset($goodsArr[$key]);
        }
    }

    $goodsArr = bubbleSort($goodsArr, $sort, $type);
    /* 重组 */
    foreach ($goodsArr as $key => $value) {
        $goodsArr2[$value['B']][] = $value;
    }

    if (!empty($purchases)) {
        foreach ($purchases as $key => $value) {
            $purchases2[$value['add_time']][] = $value;
        }
    }

    // 取得0销量的商品
    $skuStr = implode(',', $skuArr);
    $sql = "SELECT gs.goods_xprice, gs.goods_sku AS sku, g.goods_name, ga.attr_value AS goods_attr, gs.goods_number AS stock FROM {$ecs->table('goods_stock')} gs LEFT JOIN {$ecs->table('goods')} g ON g.goods_id = gs.goods_id LEFT JOIN {$ecs->table('goods_attr')} ga ON ga.goods_attr_id = gs.goods_attr_id WHERE gs.goods_sku NOT IN(" . implode(',', $skuArr2) . ") AND gs.area_id = 3 AND g.is_on_sale = 1 AND g.is_taodan = 0 ORDER BY gs.goods_number DESC";
    $data2 = $db->getAll($sql);

    $smarty->assign('__PUC__', __PUC__);
    $smarty->assign('end_date', $end_date);
    $smarty->assign('start_date', $start_date);
    $smarty->assign('data', $goodsArr2);
    $smarty->assign('data2', $data2);
    $smarty->assign('purchases', $purchases2);
    $smarty->display('purchases/purchases.htm');
}

/* 标记为正在进货 */
elseif ($_REQUEST['act'] == 'pcs') {
    if (!empty($_REQUEST['sku'])) {
        $sql = "INSERT INTO egg_ware_purchases (sku, name) VALUES ";
        $sqlVal = array();
        foreach ($_REQUEST['sku'] as $key => $value) {
            $sqlVal[] = "('{$value}', '{$_REQUEST['name'][$value]}')";
        }
        $sql .= implode(',', $sqlVal);
        $db->query($sql);
    }
    header("location:{$_SERVER['HTTP_REFERER']}");
}

/* 标记为已经到货 */
elseif ($_REQUEST['act'] == 'ischeck') {
    if (!empty($_REQUEST['id'])) {
        foreach ($_REQUEST['id'] as $key => $value) {
            $sql = "UPDATE egg_ware_purchases SET is_check = 1 WHERE id = {$value}";
            $db->query($sql);
        }
    }
    header("location:{$_SERVER['HTTP_REFERER']}");
}
